<template>
    <div>
        <!--        //商品管理参数列表-->
        <breadcrumb :nav-data="['商品管理','参数列表']"></breadcrumb>
        <el-card>
            <el-alert
                title="注意：只允许为第三级分类设置相关参数！"
                type="warning"
                show-icon
                :closable="false"
                effect="dark">
            </el-alert>
            <el-row>
                <el-col>
                    <span>选择商品分类：</span>
                    <!--                    级联选择器-->
                    <el-cascader
                        v-model="selectKeys"
                        @change="onCascaderChange"
                        :options="cascaderOptions"
                        :props="cascaderProps"></el-cascader>
                </el-col>
            </el-row>
            <el-tabs v-model="activeName" type="border-card" @tab-click="changeTabClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button @click="addParamsVisible=true" :disabled="isBtnDisabled" type="primary" size="mini">
                        添加参数
                    </el-button>
                    <!--分类列表-->
                    <el-table
                        :data="manyTableData"
                        border
                        style="width: 100%">
                        <!--                        展开行-->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag
                                    :key="index"
                                    v-for="(tag,index) in scope.row.attr_values"
                                    closable
                                    :disable-transitions="false"
                                    @close="onDeleteAttr(scope.row, index)">
                                    {{ tag }}
                                </el-tag>
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="onAddAttr(scope.row)"
                                    @blur="onAddAttr(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small"
                                           @click="onShowAddAttrInput(scope.row)">+ New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="#" type="index"></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <!--                        修改-->
                                <el-button type="primary" size="mini" @click="showEditDialog(scope.row.attr_id)"
                                           icon="el-icon-edit">修改
                                </el-button>
                                <!--                        删除-->
                                <el-button type="danger" size="mini" @click=removeParams(scope.row.attr_id)
                                           icon="el-icon-delete">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button @click="addParamsVisible=true" :disabled="isBtnDisabled" type="primary" size="mini">
                        添加属性
                    </el-button>
                    <!--分类列表-->
                    <el-table
                        :data="onlyTableData"
                        border
                        style="width: 100%">
                        <!--                        展开行-->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag
                                    :key="index"
                                    v-for="(tag,index) in scope.row.attr_values"
                                    closable
                                    :disable-transitions="false"
                                    @close="onDeleteAttr(scope.row, index)">
                                    {{ tag }}
                                </el-tag>
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="onAddAttr(scope.row)"
                                    @blur="onAddAttr(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small"
                                           @click="onShowAddAttrInput(scope.row)">+ New Tag
                                </el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="#" type="index"></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <!--                        修改-->
                                <el-button type="primary" size="mini" @click="showEditDialog(scope.row.attr_id)"
                                           icon="el-icon-edit">修改
                                </el-button>
                                <!--                        删除-->
                                <el-button type="danger" size="mini" @click=removeParams(scope.row.attr_id)
                                           icon="el-icon-delete">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!--        添加参数-->
        <el-dialog :title="'添加'+titleText" :visible.sync="addParamsVisible">
            <el-form :model="addParams" :rules="addParamsRules" ref="addParamsForm" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addParams.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addParamsVisible = false">取 消</el-button>
                <el-button type="primary" @click="onAddParams">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 修改参数的对话框 -->
        <el-dialog :title="'修改' + titleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
            <!-- 添加参数的对话框 -->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: "Params",
    created() {
        this.getCategoriesData();
    },
    data() {
        return {
            //被激活的选项卡名称
            activeName: 'many',
            //分类级联选择器
            cascaderOptions: [],
            //分类级联选择器配置项
            cascaderProps: {
                expandTrigger: 'hover',
                value: "cat_id",
                label: "cat_name",
                children: "children"
            },
            //分类级联选择器数据绑定
            selectKeys: [],
            //动态参数的数据
            manyTableData: [],
            //静态属性的数据
            onlyTableData: [],
            //添加参数对话框显示隐藏
            addParamsVisible: false,
            //添加参数表单
            addParams: {
                attr_name: "",
                attr_sel: ""
            },
            //添加参数验证
            addParamsRules: {
                attr_name: [
                    {required: true, message: '请输入分类名称', trigger: 'blur'},
                ]
            },
            // 控制修改对话框的显示与隐藏
            editDialogVisible: false,
            // 修改的表单数据对象
            editForm: {},
            // 修改表单的验证规则对象
            editFormRules: {
                attr_name: [
                    {required: true, message: '请输入参数名称', trigger: 'blur'}
                ]
            }
        }
    },
    methods: {
        //获取分类数据
        async getCategoriesData() {
            let {data: res} = await this.$http.get("categories")
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
            this.cascaderOptions = res.data;
        },
        //选项卡切换事件
        changeTabClick() {
            console.log(this.activeName);
            this.getCategoriesAttrData()
        },

        //分类级联选择器change事件
        onCascaderChange() {
            console.log("当前被选中的节点id", this.selectKeys);
            //获取当前分类的参数
            this.getCategoriesAttrData();
        },
        //获取分类参数和属性
        async getCategoriesAttrData() {
            //通过selectKeys来确定当前要添加的分类他的父级分类id和分类等级
            if (this.selectKeys.length !== 3) {//不是三级分类
                this.onlyTableData = [];
                this.manyTableData = [];
                this.selectKeys = [];
                return this.$message.warning("只允许为三级分类设置参数！")
            }
            let {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {
                params: {
                    sel: this.activeName
                }
            });
            console.log(res);
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg);

            /* item==>
            attr_id: 5027
            attr_name: "1234"
            attr_sel: "many"
            attr_vals: "123,23,44"
            attr_write: "list"
            cat_id: 4154
            delete_time: null
            */
            res.data.forEach((item) => {
                item.attr_values = item.attr_vals ? item.attr_vals.split(",") : [];
                item.inputVisible = false;
                item.inputValue = "";
            })
            if (this.activeName === "many") {
                this.manyTableData = res.data;
            } else {
                this.onlyTableData = res.data;
            }
        },
        //确定添加参数
        onAddParams() {
            this.$refs.addParamsForm.validate(async (valid) => {
                //如果valid为true 则表示整个表单内的校验都通过了
                if (!valid) return;
                //通过校验
                let {data: res} = await this.$http.post(`categories/${this.cateId}/attributes`, {
                    attr_name: this.addParams.attr_name,
                    attr_sel: this.activeName
                })
                this.addParams.attr_name = "";
                if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
                this.getCategoriesAttrData();
                this.$message.success(res.meta.msg);
                this.addParamsVisible = false;
            })
        },
        //修改参数
        onEditParams() {
        },
        //删除参数
        onDeleteParams() {
        },
        //展示添加属性input框
        onShowAddAttrInput(row) {
            //让当前的添加属性input组件展示
            row.inputVisible = true;//只是在虚拟DOM中对input组件进行了展示,此时真实DOM还没有更新
            //获取当前el-input(saveTagInput)组件并且在这个(saveTagInput)组件中获取input标签,然后给这个标签执行focus方法
            // this.$refs.saveTagInput.$refs.input.focus();//报错找不到第二个$refs,因为saveTagInput是undefined
            // console.log(this.$refs);//=>{}
            // console.log(this.$refs.saveTagInput);//=>undefined
            //真实DOM没有更新的话,直接调用(this.$refs.saveTagInput)是找不到这个组件的

            //当虚拟DOM更新完,并且渲染到真实DOM结构之后 再去执行回调函数函数中的内容
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        //更新所有的属性
        async updateAttrValues(row, curAddAttr){
            //之前所有的属性
            let curAttrVlas = row.attr_values.join(",");
            // curAttrVlas.push(curAddAttr);
            //通过字符串拼接的形式来去把当前新增的属性给放入要传递给后端的属性字符串中
            let attr_vals = curAddAttr?curAttrVlas + "," + curAddAttr:curAttrVlas;
            //发起ajax请求
            let {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
                attr_name: row.attr_name,
                attr_sel: row.attr_sel,
                attr_vals: attr_vals
            });
            if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
            this.$message.success(res.meta.msg);
            // console.log(row,res.data);
            // Object.assign(row, res.data);
            //把后端返回的数据更新到原有行数据中,并且同步更新attr_values
            row.attr_vals = res.data.attr_vals;
            row.attr_values = row.attr_vals.split(",")
        },
        //确定为某一个参数添加属性
        onAddAttr(row) {
            //当前输入的内容
            let curAddAttr = row.inputValue;
            row.inputValue = "";//清空输入框的内容
            row.inputVisible = false;
            //非空验证
            if(curAddAttr.trim().length === 0) return
            this.updateAttrValues(row, curAddAttr)

        },
        //删除参数的某一个属性
        onDeleteAttr(row, index) {
            console.log("删除参数的某一个属性");
            row.attr_values.splice(index,1)
            this.updateAttrValues(row)
        },
        // 点击按钮，展示修改的对话框
        async showEditDialog(attrId) {
            // 查询当前参数的信息
            const {data: res} = await this.$http.get(
                `categories/${this.cateId}/attributes/${attrId}`,
                {
                    params: {attr_sel: this.activeName}
                }
            )

            if (res.meta.status !== 200) {
                return this.$message.error('获取参数信息失败！')
            }

            this.editForm = res.data
            this.editDialogVisible = true
        },
        // 重置修改的表单
        editDialogClosed() {
            this.$refs.editFormRef.resetFields()
        },
        // 点击按钮，修改参数信息
        editParams() {
            this.$refs.editFormRef.validate(async valid => {
                if (!valid) return
                const {data: res} = await this.$http.put(
                    `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
                    {attr_name: this.editForm.attr_name, attr_sel: this.activeName}
                )

                if (res.meta.status !== 200) {
                    return this.$message.error('修改参数失败！')
                }

                this.$message.success('修改参数成功！')
                this.getCategoriesAttrData()
                this.editDialogVisible = false
            })
        },
        // 根据Id删除对应的参数项
        async removeParams(attrId) {
            const confirmResult = await this.$confirm(
                '此操作将永久删除该参数, 是否继续?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).catch(err => err)

            // 用户取消了删除的操作
            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除！')
            }

            // 删除的业务逻辑
            const {data: res} = await this.$http.delete(
                `categories/${this.cateId}/attributes/${attrId}`
            )

            if (res.meta.status !== 200) {
                return this.$message.error('删除参数失败！')
            }

            this.$message.success('删除参数成功！')
            this.getCategoriesAttrData()
        },
    },
    //计算属性
    computed: {
        //当前选中的三级分类id
        cateId() {
            //先取出分类id 因为在之前已经判断过了必须长度为3 所以这边可以直接取值
            return this.selectKeys.length === 3 ? this.selectKeys[2] : null
        },
        //添加参数按钮禁用启用
        isBtnDisabled() {
            //当前分类是不是三级分类
            return this.selectKeys.length !== 3
        },
        //添加参数对话框标题文本
        titleText() {
            return this.activeName === "many"?"动态参数":"静态属性"
        }
    },
    //监听属性
    watch: {
        selectKeys(value, oldValue) {
            console.log(value, oldValue);
            //发起ajax

        }
    }
}
</script>

<style scoped>
.el-row {
    margin-top: 20px;
    margin-bottom: 20px;
}

.el-tag {
    margin-left: 10px;
}

.input-new-tag {
    width: 90px;
    margin-left: 10px;
}

.button-new-tag {
    margin-left: 10px;
}
</style>